import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import {Link} from 'dva/router';
import {Table, Button,Row,Col,Layout, Menu,Form,Checkbox, Breadcrumb,Dropdown,Icon,Input,message,Radio} from 'antd';
import request from '../utils/request';
import style from '../styles/login.less';
import stylet from '../styles/TableCss.less';
import Home from './Home.js';
import {numvail,selectvail} from '../utils/Validator.js'
import QueueAnim from 'rc-queue-anim';
import enquire from 'enquire.js';
import NumericInput from '../components/NumericInput.js'
import reqwest from 'reqwest'
import {reqwest_post} from '../utils/Reqwest.js'
const phoneReg =/^1[34578]\d{9}$/g;
const {Footer} = Layout;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
class Regiser extends React.Component{
	constructor(props){
		super(props);
		this.state={
      visible:false,
      t:this.props.location.query.t,
      code:'发送验证码',
      timer:60,
      reg_phone:0,
		}
	}
  codeServer(){
    const {reg_phone} =this.state;
    reqwest_post('/api/valid_codes',{
      mobile:reg_phone
    },(data)=>{
      if(data.status=='success'){
        message.success(data.msg,0.5,()=>{

          },
        )
      }else{
        message.error(data.msg,1)
      }
    })
    // reqwest({
    //   url: window.host+'/api/valid_codes',
    //   method: 'post',
    //   crossOrigin: true,
    //   type: 'json',
    //   data:{mobile:reg_phone
    //   },

    // }).then((data) => {
    //   console.log(data);
    //   if(data.status=='success'){
    //     message.success(data.msg,0.5,()=>{

    //       },
    //     )
    //   }else{
    //     message.error(data.msg,1)
    //   }

    // }).fail((err,msg)=>{
    //   message.error(err,0.5)
    // });
  }
  handleCodeClick(){
    let _this = this;
    let _timer = this.state.timer;
    if(this.state.code=='发送验证码'&&this.state.reg_phone.length==11){
      if(_timer==60){
        _this.codeServer()
        _this.setState({code:'60秒后重发'})
        _this.props.form.setFieldsValue({'phonecode':''})
      }
      this.timeoutId = setInterval(() => {
        _timer--
        // _this.setState({timer:_timer});
        if(_this.state.timer>0){
            _this.setState({code:_timer +'秒后重发',timer:_timer})
            console.log(1)
          }else if(_this.state.timer<=0){
            _this.setState({code:'发送验证码',timer:60})
            clearInterval(_this.timeoutId)
          }
        }, 1000)
    }else{
      this.props.form.setFields({
        logphone:{
          errors:[new Error('请输入手机号')]
        }
      })
    }
  }
  loadserver(_data={}){
    let _this = this;
    reqwest({
      url: window.host+'/api/registrations',
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{user:{name:_data.userName,mobile:_data.phone,password:_data.password},
        account:{name:_data.priseName,type:_data.type},
        valid_code:_data.phonecode
      },

    }).then((data) => {
      console.log(data);
      if(data.status=='success'){
        // let set ={"mobile":data.current_user.mobile,"avatar":data.current_user.avatar,"avatar_url":data.current_user.avatar_url,"name":data.current_user.name,"role":data.current_user.role,"accout_name":data.current_user.account.name}
          let set ={"mobile":data.current_user.mobile,"avatar":data.current_user.avatar,"avatar_url":data.current_user.avatar_url,"name":data.current_user.name,"role":data.current_user.role,"accout_name":data.current_user.account.name,"invit_url":data.current_user.account.invit_url}

          message.success('注册成功,将直接跳往首页',1,()=>{
            window.localStorage['token']=data.token;
            window.localStorage['curloe']=data.current_user.role;
            // debugger
            window.localStorage['menu']=JSON.stringify(data.menu);
            window.localStorage['cgj_id']=data.current_user.cgj_user_id;
            window.localStorage['account_type']=data.current_user.account_type;
            window.localStorage['userrr_id']=data.current_user.id;
            window.localStorage['setting']=JSON.stringify(set);
            // console.log(data.wallet)
            // window.localStorage['money'] = JSON.stringify(data.current_user.wallet)
            // window.localStorage['companies']=JSON.stringify(data.companies);
            window.sessionStorage['material']=JSON.stringify(data.materials);
            // window.sessionStorage['store_tree']=JSON.stringify(data.stores_tree);
            // window.location.hash=window.location.hash
            // window.location.hash='/app/home?curren=1';
            _this.context.router.replace('/app/home?current=1')
          }
        )

      }else{
        _this.setState({loading:false});
        message.error(data.msg)
      }
    }).fail((err,msg)=>{
      console.log(err)
    });
  }
	handleSubmit(e){
            // this.context.router.replace('/app/home?current=1')

    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log(values.priseType);
      if (!err) {
        this.loadserver({phone:values.logphone,phonecode:values.phonecode,password:values.password1,userName:values.userName,priseName:values.priseName,type:values.priseType})
      }else{
        message.warning('请输出必填项');
      }
    });
	}
  componentWillMount(){
    clearInterval(this.timeoutId)

    // this.props.form.resetFields(null);
  }
  componentDidMount(){
    this.props.form.resetFields();
    // this.props.form.setFieldsValue
    console.log(this.props)

  }
  componentWillUnmount() {
    clearInterval(this.timeoutId)
  }
	render(){
		const { getFieldDecorator,setFields } = this.props.form;

		return <Layout className={`${style.auth}`}>
        <Col className={`${style.auth_content}`}>
          <h1>注册</h1>
          <Form className={`${style.auth_form}`} hideRequiredMark={true} onSubmit={this.handleSubmit.bind(this)}>
            <FormItem className={`${style.input_group}`}>
              {getFieldDecorator('logphone', {
                rules: [
                  {
                    required: true,
                    len: 11,
                    pattern: phoneReg,
                    type: 'string',
                    message: '请输入用户名',
                    validator: (rule, value, callback) => {
                      numvail(rule, value, callback)
                    }
                  }
                ]
              })(<Input onChange={e => {
                    this.setState({ reg_phone: e.target.value })
                  }} prefix={<Icon type="mobile" style={{ fontSize: 14 }} />} placeholder="手机" />)}
            </FormItem>
            <FormItem className={`${style.input_group} ${style.send_code_btn}`}>
              {getFieldDecorator('phonecode', {
                initialValue: undefined,
                rules: [{ required: true, message: '请输入验证码' }]
              })(<Input addonAfter={<span
                      onClick={this.handleCodeClick.bind(this)}
                    >
                      {this.state.code}
                    </span>} prefix={<Icon type="lock" style={{ fontSize: 14 }} />} placeholder="请输入验证码" />)}
            </FormItem>
            <FormItem className={`${style.input_group}`}>
              {getFieldDecorator('password1', {
                initialValue: undefined,
                rules: [{ required: true, message: '请输入密码' }]
              })(<Input onFocus={e => {
                    if (e.target.value == '请输入密码') {
                      e.target.value = ''
                    }
                  }} prefix={<Icon type="lock" style={{ fontSize: 14 }} />} type="password" placeholder="密码 (6位以上，区分大小写)" />)}
            </FormItem>
            <FormItem className={`${style.input_group}`}>
              {getFieldDecorator('userName', {
                rules: [{ required: true, message: '请输入姓名' }]
              })(<Input prefix={<Icon type="user" style={{ fontSize: 14 }} />} placeholder="姓名" />)}
            </FormItem>
            <FormItem className={`${style.input_group}`}>
              {getFieldDecorator('priseName', {
                rules: [{ required: true, message: '请输入企业名称' }]
              })(<Input onChange={e => {
                    this.setState({ priseName: e.target.value })
                  }} prefix={<Icon type="lock" style={{ fontSize: 14 }} />} placeholder="企业名称" />)}
            </FormItem>
            <FormItem labelCol={{ span: 6 }} label="企业类型">
              {getFieldDecorator('priseType', {
                rules: [{ message: '请输入企业类型', required: true }]
              })(<RadioGroup>
                  <Radio value="Account">品牌商</Radio>
                  <Radio value="Dealer">经销商</Radio>
                </RadioGroup>)}
            </FormItem>
            <FormItem className={`${style.input_group}`}>
              <Button type="primary" htmlType="submit" className={`${style.submit_btn}`}>
                注册
              </Button>
            </FormItem>

            <FormItem className={`${style.links}`}>
              <Link to={{ pathname: '/log' }}>去登录</Link>
            </FormItem>
          </Form>
        </Col>
      </Layout>
	}
}
// onFocus={(e)=>{if(e.target.value=='请输入验证码'){e.target.value=''};}}
const RegiserForm = Form.create()(Regiser);
Regiser.contextTypes = {
  router: PropTypes.object
};
export default connect()(RegiserForm);
